package com.wangijun.yuan.core.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 功能描述: 根据ID获取归属地
 *
 * @author wlf 2024/3/26 11:09
 */
@Slf4j
public class IpUtil {

    /**
     * 功能描述: 获取地址
     *
     * @author wlf 2024/3/26 13:49
     */
    public static String getAddr() {
        try {

            return baiduIpQuery(SpringMvcUtil.getIpAddr());
        } catch (Exception e){
            log.error("获取归属地错误",e);
            return "未知";
        }
    }

    /**
     * 功能描述: 百度的根据IP查询地址
     *
     * @author wlf 2024/3/26 13:48
     */
    private static String baiduIpQuery(String ip) {

        /*返回的样例报文*/
        /*
        * {
    "status": "0",
    "t": "",
    "set_cache_time": "",
    "data": [
        {
            "ExtendedLocation": "",
            "OriginQuery": "117.136.12.79",
            "appinfo": "",
            "disp_type": 0,
            "fetchkey": "117.136.12.79",
            "location": "广东省广州市 移动",
            "origip": "117.136.12.79",
            "origipquery": "117.136.12.79",
            "resourceid": "6006",
            "role_id": 0,
            "shareImage": 1,
            "showLikeShare": 1,
            "showlamp": "1",
            "titlecont": "IP地址查询",
            "tplt": "ip"
        }
    ]
}
        * */
        String url = "https://opendata.baidu.com/api.php?query={}&co=&resource_id=6006&oe=utf8";
        if (ip.equals("127.0.0.1")){
            return "localhost";
        }
        String body = HttpUtil.get(StrUtil.format(url, ip));
        JSONObject entries = JSONUtil.parseObj(body);
        JSONArray jsonArray = entries.getJSONArray("data");
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        return jsonObject.getStr("location");
    }

}
